package com.example.atools;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Date;

import com.anhthao.nuotcabe.R;
import android.R.bool;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;

public class Tools {

	// Hàm đ�?c một Url thành kết quả string
	public static String downloadUrlToString(String sUrl) {
		try {
			URL address;
			address = new URL(sUrl);
			URLConnection conn = address.openConnection();// new
															// URLConnection(address);
			conn.setConnectTimeout(15000);
			conn.setReadTimeout(15000);
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] contents = new byte[1024];
			int bytesRead = 0;
			String strFileContents, sResult = "";
			while ((bytesRead = bis.read(contents)) != -1) {
				strFileContents = new String(contents, 0, bytesRead);
				sResult += strFileContents;
			}
			return sResult;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static boolean isNetworkAvailable(Context con) {
		ConnectivityManager connectivityManager;
		boolean connected = false;

		try {
			connectivityManager = (ConnectivityManager) con
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectivityManager
					.getActiveNetworkInfo();
			connected = networkInfo != null && networkInfo.isAvailable()
					&& networkInfo.isConnected();
			return connected;
		} catch (Exception e) {
			System.out
					.println("CheckConnectivity Exception: " + e.getMessage());
			// Log.v("connectivity", e.toString());
		}

		return connected;

	}

	/**
	 * Hàm hiển thị Msg xong tự mất
	 * 
	 * @param ctx
	 *            G�?i hàm getBaseContext của Activity
	 * @param sMsg
	 */
	public static void showPopMsg(Context ctx, String sMsg) {
		Toast.makeText(ctx, sMsg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * Hàm hiển thị Msg dạng Dialog trên màn hình, ngư�?i dùng phải bấm Ok để
	 * đóng lại
	 * 
	 * @param ctx
	 *            Có thể truy�?n thẳng Activity
	 * @param sMsg
	 */
	public static void showAlertMsg(Context ctx, String sTitle, String sMsg) {
		// Hiện dialog confirm
		AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
		alertDialog.setTitle(sTitle);
		alertDialog.setMessage(sMsg);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// here you can add functions
			}
		});
		// alertDialog.setIcon(R.drawable.icon);
		alertDialog.show();
	}

	public static boolean stringIsNullOrEmpty(String s) {
		if (s == null || s.length() == 0)
			return true;
		return false;
	}

	/**
	 * Hàm chung xử lý tham số push. Nếu thông điệp dạng riêng thì g�?i tới hàm
	 * xử lý riêng
	 */
	public static void generateNotification(Context context, String message,
			int idType) {
		// -parse message
		String[] arr = message.split("#");
		if (arr.length < 2) {
			arr = new String[2];
			arr[0] = "The gioi giai tri";
			arr[1] = "http://sieugiaitri.us";
		} else if (arr.length > 3) // từ 4 tham số trở lên: xử lý riêng
		{
			// Cài đặt hàm xử lý tham số riêng ở
			// đây..................................................
			// generateNotification_cus(context, arr);
			// return;
		}

		// Từ 3 tham số trở lại: xử lý chung
		int icon = android.R.drawable.ic_dialog_email;// ic_input_add (+, mau),
												// ic_menu_info_details;//R.drawable.title_bar;

		long when = System.currentTimeMillis();

		String title = arr[0];// context.getString(R.string.app_name);
		message = arr[1];
		// -
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, title, when);

		PendingIntent intent;
		// Intent notificationIntent = new Intent(context, MainActivity.class);
		Intent notificationIntent = new Intent(Intent.ACTION_VIEW,
				Uri.parse(arr[1]));
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		if (arr.length >= 3) {
			if (arr[2].equalsIgnoreCase("C") || arr[2].equalsIgnoreCase("RC"))
				notification.defaults |= Notification.DEFAULT_SOUND;
			if (arr[2].equalsIgnoreCase("R") || arr[2].equalsIgnoreCase("RC"))
				notification.defaults |= Notification.DEFAULT_VIBRATE;
		} else {
			// Play default notification sound
			notification.defaults |= Notification.DEFAULT_SOUND;

			// Vibrate if vibrate is enabled
			notification.defaults |= Notification.DEFAULT_VIBRATE;
		}

		if (idType == 0)
			notificationManager.notify(0, notification);
		else if (idType == -1) {
			int randomNum = 1 + (int) (Math.random() * 10);// (int)(Math.random()*1000000);
			notificationManager.notify(randomNum, notification);
		} else
			notificationManager.notify(idType, notification);

	}

	public static String getEmail(Context context) {
		String sEmail = "";
		try {
			AccountManager accountManager = AccountManager.get(context);
			Account[] accounts = accountManager.getAccountsByType("com.google");
			for (int i = 0; i < accounts.length; i++) {
				if (sEmail.length() == 0)
					sEmail = accounts[i].name;
				else
					sEmail += ";" + accounts[i].name;
			}
		} catch (Exception e) {
		}
		if (sEmail.length() == 0)
			sEmail = "null";
		return sEmail;

		// //
		// Account account = getAccount(accountManager);
		//
		// if (account == null) {
		// return null;
		// } else {
		// return account.name;
		// }
	}

	private static Account getAccount(AccountManager accountManager) {
		Account[] accounts = accountManager.getAccountsByType("com.google");
		Account account;
		if (accounts.length > 0) {
			account = accounts[0];
		} else {
			account = null;
		}
		return account;
	}

	public static void setAlarm(Context ctx) {
		setAlarm(ctx, MyConstant.mFreqStart, MyConstant.mFreqSec);
	}

	public static void setAlarm(Context ctx, String timeStart, int iFreqSec) {
		Intent localIntent = new Intent(ctx, MyScheRcv.class);
		localIntent.putExtra("NotifID", 1);
		PendingIntent localPendingIntent = PendingIntent.getBroadcast(ctx, 0,
				localIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager localAlarmManager = (AlarmManager) ctx
				.getSystemService(Context.ALARM_SERVICE);
		Calendar localCalendar = Calendar.getInstance();
		// localCalendar.set(11, 16); //HOUR_OF_DAY
		// localCalendar.set(12, 0); //MINUTE
		// localCalendar.set(13, 0); //SECOND
		// localAlarmManager.setRepeating(0, localCalendar.getTimeInMillis(),
		// 60000L, localPendingIntent);

		String s;
		int i;
		if (timeStart == null || timeStart.length() == 0
				|| timeStart.equalsIgnoreCase("null"))
			localAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
					localCalendar.getTimeInMillis(), iFreqSec * 1000,
					localPendingIntent);
		else if (timeStart.startsWith("+")) // Bắt đầu sau bao nhiêu giây
		{
			s = timeStart.substring(1);
			i = convertInt(s, 3600);
			localCalendar.setTimeInMillis(localCalendar.getTimeInMillis() + i
					* 1000);
			localAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
					localCalendar.getTimeInMillis(), iFreqSec * 1000,
					localPendingIntent);
		} else { // Bắt đầu theo thời gian cụ thể
			int iH, iM, iS;
			Date d = new Date();
			iH = d.getHours();
			iM = d.getMinutes();
			iS = d.getSeconds();
			String[] arr = timeStart.split(":");
			if (arr.length > 0)
				iH = convertInt(arr[0], d.getHours());
			if (arr.length > 1)
				iM = convertInt(arr[1], d.getMinutes());
			if (arr.length > 2)
				iS = convertInt(arr[2], d.getSeconds());
			localCalendar.set(Calendar.HOUR_OF_DAY, iH); // HOUR_OF_DAY
			localCalendar.set(Calendar.MINUTE, iM);
			localCalendar.set(Calendar.SECOND, iS);
			localAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
					localCalendar.getTimeInMillis(), iFreqSec * 1000,
					localPendingIntent);
		}

	}

	public static int convertInt(String s, int iDefault) {
		try {
			if (isStrNullOrEmpty(s))
				return iDefault;
			s = s.trim();
			int i = Integer.parseInt(s);
			return i;
		} catch (Exception ex) {
		}
		return iDefault;
	}

	public static void cancelAlarm(Context ctx) {
		Intent intent = new Intent(ctx, MyScheRcv.class);
		PendingIntent sender = PendingIntent.getBroadcast(ctx, 0, intent, 0);
		AlarmManager alarmManager = (AlarmManager) ctx
				.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
	}

	public static String getImei(Context ctx) {
		String deviceid = null;
		TelephonyManager tManager;
		try {
			tManager = (TelephonyManager) ctx.getApplicationContext()
					.getSystemService(Context.TELEPHONY_SERVICE);
			deviceid = tManager.getDeviceId();
		} catch (Exception e) {
		}
		;
		if (deviceid == null)
			deviceid = "null";
		return "" + deviceid;
	}

	// Tham khảo:
	// http://android-developers.blogspot.com/2011/03/identifying-app-installations.html
	// http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id
	@SuppressLint("NewApi")
	public static String getDeviceId(Context ctx) {
		String androidid, deviceid = null, sHard;
		TelephonyManager tManager;
		try {
			androidid = Secure.getString(ctx.getApplicationContext()
					.getContentResolver(), Secure.ANDROID_ID);
		} catch (Exception e) {
			androidid = "null";
		}
		;

		try {
			tManager = (TelephonyManager) ctx.getApplicationContext()
					.getSystemService(Context.TELEPHONY_SERVICE);
			deviceid = tManager.getDeviceId();
		} catch (Exception e) {
		}
		;

		if (deviceid == null)
			deviceid = "null";
		// Ghép imei và androidid
		deviceid += "-" + androidid;
		// Lấy thông tin phần cứng
		try {
			sHard = "" + Build.BOARD.length() % 10 + Build.BRAND.length() % 10
					+ Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10
					+
					// Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
					// Build.ID.length()%10 +
					Build.MANUFACTURER.length() % 10 + Build.MODEL.length()
					% 10 + Build.PRODUCT.length() % 10 +
					// Build.TAGS.length()%10 + Build.TYPE.length()%10 +
					// Build.USER.length()%10 ; //13 digits
					"";
			// Nối thêm serial nếu lấy được
			String serial = null;
			if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
				serial = Build.SERIAL;
				if (serial != null && serial != "unknown") {
					if (serial.length() > 6) // lấy 3 ký tự đầu và 3 ký tự cuối
						sHard += serial.substring(0, 3)
								+ serial.substring(serial.length() - 4) + "s";
					else
						sHard += serial + "s";
				}
			}
			sHard = sHard.replace("-", "x");// Loại trừ ký hiệu ngăn cách

		} catch (Exception e) {
			sHard = "null";
		}

		deviceid += "-" + sHard;

		return deviceid;
	}

	// Lấy độ phân giải màn hình
	public static String getScreenResolution(Context ctx) {
		try {
			DisplayMetrics displayMetrics = new DisplayMetrics();
			WindowManager wm = (WindowManager) ctx.getApplicationContext()
					.getSystemService(Context.WINDOW_SERVICE); // the results
																// will be
																// higher than
																// using the
																// activity
																// context
																// object or the
																// getWindowManager()
																// shortcut
			wm.getDefaultDisplay().getMetrics(displayMetrics);
			int screenWidth = displayMetrics.widthPixels;
			int screenHeight = displayMetrics.heightPixels;
			return screenWidth + "x" + screenHeight;
		} catch (Exception e) {
		}
		return "";
	}

	public static String getDevicePhoneType(Context ctx) {
		try {
			TelephonyManager manager = (TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE);
			if (manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
				return "TabletType";
			} else {
				return "MobileType";
			}
		} catch (Exception e) {
		}
		return "unknown";
	}

	public static String getDeviceSizeType(Context ctx) {
		try {
			// Compute screen size
			DisplayMetrics dm = ctx.getResources().getDisplayMetrics();
			float screenWidth = dm.widthPixels / dm.xdpi;
			float screenHeight = dm.heightPixels / dm.ydpi;
			double size = Math.sqrt(Math.pow(screenWidth, 2)
					+ Math.pow(screenHeight, 2));
			// Tablet devices should have a screen size greater than 6 inches
			if (size >= 6)
				return "TabletSize";
			else
				return "MobileSize";
		} catch (Exception e) {
		}
		return "unknown";
	}

	public static String getScreenSize_Inches(Context ctx) {
		try {
			// Compute screen size
			DisplayMetrics dm = ctx.getResources().getDisplayMetrics();
			float screenWidth = dm.widthPixels / dm.xdpi;
			float screenHeight = dm.heightPixels / dm.ydpi;
			double size = Math.sqrt(Math.pow(screenWidth, 2)
					+ Math.pow(screenHeight, 2));
			// Tablet devices should have a screen size greater than 6 inches
			return String.format("%.2f", size);
		} catch (Exception e) {
		}
		return "";
	}

	public static boolean isStrNullOrEmpty(String s) {
		if (s == null)
			return true;
		s = s.trim();
		if (s.length() == 0)
			return true;
		return false;
	}

}
